/**

This file is part of MaCI/GIMnet.

MaCI/GIMnet is free software: you can redistribute it and/or modify it 
under the terms of the GNU Lesser General Public License as published 
by the Free Software Foundation, either version 3 of the License, or 
(at your option) any later version.

MaCI/GIMnet is distributed in the hope that it will be useful, but WITHOUT 
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 
FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public 
License for more details.

You should have received a copy of the GNU Lesser General Public 
License along with GIMnet. (See COPYING.LESSER) If not, see 
<http://www.gnu.org/licenses/>.

**/
/**
 *
 * $Id: TextServer.cpp,v 1.5 2009-07-20 08:47:24 morsko Exp $
 *
 * \file
 * \brief MaCI - Implementation of Text Server interface
 * \author Matthieu Myrsky <matthieu.myrsky@tkk.fi>
 */
#include "TextServer.hpp"
//*****************************************************************************
#define GIMI_CLIENT_API (20000)
#include "gimi.h"
//*****************************************************************************
//*****************************************************************************
using namespace MaCI::Text;
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************


CTextServer::CTextServer(MaCICtrl::CMaCICtrlServer *aMaCICtrlServerPtr, const int aInterfaceMinor)
  : CMaCI(aMaCICtrlServerPtr, GIMI_PROTOCOL_MACI_TEXT, aInterfaceMinor),
    CThread(1),
    CSync(1,1),
    iServerActive(false),
    iTextCommandArray(),
    iReplyDataArray()
{


}
//*****************************************************************************

CTextServer::~CTextServer()
{
  Close();
}
//*****************************************************************************

MaCI::EMaCIError CTextServer::DoOpen(void)
{
  EMaCIError result = KMaCIError;
  assert(this != NULL);
  assert(iGIMIPtr != NULL);

  if(!iServerActive){
    RegisterProvidedService("MaCI - Text Interface");
    RegisterAcceptedService("MaCI - Text CommandInterface");
    iGIMIPtr->setQueueMaxSize(GIMI_PROTOCOL_MACI_TEXT,iInterfaceMinor,1000,iRedirectionBufferId);
    iServerActive = true;
    CThread::RunThread();
    result = KMaCIOK;
  }else{
    dPrint(3, "Server already opened");

  }
  return result;
}
//*****************************************************************************

MaCI::EMaCIError CTextServer::DoClose(void)
{
 EMaCIError result = KMaCIError;
 assert(this != NULL);
 assert(iGIMIPtr != NULL);
 if (iServerActive) {
   // Unregister services
    UnregisterProvidedService();
    UnregisterAcceptedService();
   // Stop the handler Thread
   iServerActive = false;
   ///* CThread::CancelThread(); //Removed by script */
   //CThread::WaitThread();
 }
 return result;
}
//*****************************************************************************

MaCI::EMaCIError CTextServer::WaitCommand(CTextData &aData,
                                          TReplyInfo &aInfo,
                                          const unsigned int aTimeout_ms,
                                          bool aSkipQueued)
{
  EMaCIError result = KMaCIError;
  const unsigned int begin = ownTime_get_ms();
  int timeout = aTimeout_ms;
  
  aData.Reset();
  
  Lock();
  do {
    const unsigned int asize = iTextCommandArray.size();
    // Check whether there are commands in buffer.
    if (asize > 0) {
      // Got element. So; take reference of its pointer, copy it to
      // 'data', delete it. Pop the element from queue.
      const CTextData *d;
      const TReplyInfo *r;

      // Check whether we want to skip queue 
      if (aSkipQueued && asize > 1) {
        // This is only executed if there is >1 in queue.  Otherwise
        // default branch is executed.  Want to skip, so get back()
        // reference.
        d = iTextCommandArray.back();
	r= iReplyDataArray.back();
        // Copy data
        aData = *d;
	aInfo = *r;

        // Delete all elements.
        for(EACH_IN_i(iTextCommandArray)) {
          delete *i;
        }
        for(EACH_IN_i(iReplyDataArray)) {
          delete *i;
        }
        // Clear array.
        iTextCommandArray.clear();
	iReplyDataArray.clear();
        
        // print debug
        dPrint(4,"Flushed %d unprocessed commands out of buffer",
               asize-1);

      } else {
        // No skipping, so get front() reference;
        d = iTextCommandArray.front();
	r = iReplyDataArray.front();
        // Copy data.
        aData = *d;
        aInfo = *r;
        // Delete source
        delete d;
	delete r;
        // pop the entry from queue.
        iTextCommandArray.pop_front();
	iReplyDataArray.pop_front();

      }

      // Set result.
      result = KMaCIOK;
      
      // Break the loop, skipping Wait()
      break;
    }
    
    // Wait signal unconditionally.
    if (timeout > 0) Wait(timeout);
    
    // Recalculate timeout
    timeout = aTimeout_ms - ownTime_get_ms_since(begin);
  } while(timeout > 0 && iServerActive);
  Unlock();

  // Change result type if timeout was the reason.
  if (timeout <= 0 && result == KMaCIError) result = KMaCITimeout;


  return result;



}
//*****************************************************************************
bool CTextServer::SendText(const std::string &aText){

  bool result = false;
  
  assert(iGIMIPtr != NULL);
  gim::binbag::CBinBag bb;
  CTextData ttsData;
  ttsData.EncodeTo(&bb);
  ttsData.SetCommand(TCommand(KCommandSendText));
  ttsData.SetText(aText);
  ttsData.Print(10);
  EMaCIError e = 
    SendInterfaceSubscriberMessage(ttsData.GetBinBagContainerPtr()->GetBuffer(),
                                   ttsData.GetBinBagContainerPtr()->GetBufferSize());
  
  result = (e == KMaCIOK);
  
  return result;
}
//*****************************************************************************

bool CTextServer::SendTextAccomplishedMessage(const std::string &aText,
                                              TReplyInfo &aInfo)
{
 
  EMaCIError result = KMaCIError;
  if(iServerActive){

    //Pack data
    gim::binbag::CBinBag replybb;
    CTextData ttsData;
    ttsData.EncodeTo(&replybb);
    ttsData.SetCommand(TCommand(KReplyTextAccomplished));
    ttsData.SetText(aText);
    
    dPrint(8,"Sending reply");
    
    int r = iGIMIPtr->send(aInfo.senderId,
                           ttsData.GetBinBagContainerPtr()->GetBuffer(),
                           ttsData.GetBinBagContainerPtr()->GetBufferSize(),
                           iInterfaceMajor,
                           iInterfaceMinor,
                           aInfo.msgId);
    
    if (r == GIMI_OK) {
      dPrint(8,"Succesfully sent message with %d BinBag elements to '%p'",
             ttsData.GetBinBagContainerPtr()->GetElementCount(),
             aInfo.senderId);
      
      result = KMaCIOK;
      
    } else {
      
      dPrint(3,"Failed to send message with %d BinBag elements to '%p'",
             ttsData.GetBinBagContainerPtr()->GetElementCount(),
             aInfo.senderId);
    }
    
  }else{
    result = KMaCINoConnection;
    
  }
  
  return result;

}
//*****************************************************************************

int CTextServer::ThreadFunction(const int aThreadNumber)
{
  int result = 0;
  EMaCIError e;
  gimi::GIMIMessage gmsg;
  
  assert(aThreadNumber == 0);
  assert(iGIMIPtr != NULL);
  
  dPrint(4, "GIMIMessage handler started");
  
  // Run as long as the thread should be active
  while(iServerActive) {
    // Call the ReceiveMessage wrapper with 1s timeout
    e = ReceiveInterfaceMessage(gmsg, 1000);
    if (e == KMaCIOK) {
      dPrint(15,"Got GIMIMessage %d - Processing.(sender id 0x%08x)", gmsg.messageId,gmsg.senderId);
      ProcessMessage(gmsg);
      
    } else if (e != KMaCITimeout) {
      // Other error, try to recover by sleeping one second.
      ownSleep_ms(1000);
      
    }
  }
  
  dPrint(4, "GIMIMessage handler stopped");
  
  return result;

}
//*****************************************************************************

int CTextServer::ProcessMessage(const gimi::GIMIMessage &msg)
{
 int result = 0;
  gim::binbag::CBinBag bb;
  CTextData d;
  bool r;

  r = bb.Decode(msg.getData(), msg.getDatalength());
  if (r) {
    // Succesfully decoded as BinBag.
    r = d.DecodeFrom(&bb);
    if (r) {
      // Succesfully decoded as Text
      // Now, Check whether it was Command, if so, process it 
   
      const TCommand *cmd = d.GetCommand();
      if (cmd) {
        //Check the type of Command, if it's an event msg it's not for the server
	if(cmd->cmd != KCommandUnknown){
          // Default action for All commands is to save them to CommandQueue
          
          // Debug
          dPrint(8, "Got Command to be passed to User (Command wass %d)",
                 cmd->cmd);
	  CTextData *new_entry = new CTextData(d);
          TReplyInfo *new_reply = new TReplyInfo(msg.getSenderId(),msg.messageId);
          // Lock, Push, Notify, Unlock
          Lock();
          iTextCommandArray.push_back(new_entry);
          iReplyDataArray.push_back(new_reply);
          Notify();
          Unlock();
        
        }else{  

          dPrint(4,"Unidentified command! %d (%x)! Ignore.",
                 cmd->cmd, cmd->cmd);
        
        }
      }
      
    }
  }
  
  return result;
}
//*****************************************************************************
void CTextServer::ClearCommandBuffer(void)
{
  Lock();
  dPrint(8,"Clearing commandbuffer, got %d entries", iTextCommandArray.size());
  iTextCommandArray.clear();
  Unlock();
}
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
//*****************************************************************************
